<?php
class Login_fb extends CI_Controller
{
	private $user = null;
	public function __construct(){
		parent::__construct();
		parse_str($_SERVER['QUERY_STRING'], $_REQUEST);
		$this->load->library('fb_api/facebook', array("appId" => $this->config->item('appId') , "secret" => $this->config->item('secret')));
		$this->user = $this->facebook->getUser();
	}

	public function index(){
		//echo $this->facebook->getLoginUrl();
		if ($this->user) {
		  try {
		    // Proceed knowing you have a logged in user who's authenticated.
		    $user_profile = $this->facebook->api('/me');
		    //echo "<br>";
		    //print_r($user_profile);
		    $fb_email = $user_profile['email'];
		    //Kiem tra xem trong CSDL da co email nay chua
		    $check_email = $this->db->select('id, fullname, email, avatar')->get_where('member', array('email' => $fb_email));
		    if($check_email->num_rows() > 0 ) {
		    	$row = $check_email->row();
		    	$sess = array(
			    	'loginStatus' => TRUE,
			    	'sess_fullname' => $user_profile['name'],
			    	'sess_memId'	=> $row->id,
			    	'sess_memAvatar' => $row->avatar,
			    	'log_with_fb' => TRUE
		    	);
		    } else {
		    	$data_insert = array(
		    		'email'	=> $user_profile['email'],
		    		'fullname'	=> $user_profile['name'],
		    		'status'	=> 1
		    	);
		    	$this->db->insert('member', $data_insert);
		    	$memId = $this->db->insert_id();
		    	$sess = array(
			    	'loginStatus' => TRUE,
			    	'sess_fullname' => $user_profile['name'],
			    	'sess_memId'	=> $memId,
			    	'sess_memAvatar' => null,
			    	'log_with_fb' => TRUE
		    	);
		    }
		    
		    $this->session->set_userdata($sess);
		    //redirect('home');
		  } catch (FacebookApiException $e) {
		    error_log($e);
		    $user = null;
		  }
		}
		if ($this->user) {
		  $logoutUrl = $this->facebook->getLogoutUrl(array('next' => base_url().'login_fb/logout/'));
		  echo "<a href='$logoutUrl'>Logout</a>";
		} else {
		  $loginUrl = $this->facebook->getLoginUrl(array('scope' => 'email'));
		  echo "<a href='$loginUrl'>Login</a>";
		}
	}

	public function logout(){

		session_cache_limiter('private');

		$arr = array(
			'loginStatus' => FALSE,
			'sess_fullname' => '',
			'sess_memId' => ''
		);
		$this->facebook->destroySession();
		$this->session->unset_userdata($arr);
		$this->session->sess_destroy();

		header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
		header("Cache-Control: post-check=0, pre-check=0", false);
		header("Pragma: no-cache");

		redirect(base_url().'landing', 'refresh');
	}
}